using Devtodo.Models;
using Microsoft.Data.Sqlite;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System.Collections.ObjectModel;
using Windows.Storage;
namespace Devtodo.Pages;

public sealed partial class Todo : Page
{
  public Todo()
  {
    InitializeComponent();
    LoadProjectList();
  }
  public ObservableCollection<TodoItem> Items { get; } = [];
  public ObservableCollection<string> ProjectNames { get; set; } = [];
  async void LoadList()
  {
    Items.Clear();
    var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
    await connection.OpenAsync();
    var selectVersionCmd = new SqliteCommand("SELECT * FROM 'update' ul LEFT JOIN version v ON ul.versionid=v.id WHERE finished=0", connection);
    var todoReader = await selectVersionCmd.ExecuteReaderAsync();
    while (await todoReader.ReadAsync())
    {
      Items.Add(new TodoItem
      {
        Id = todoReader.GetInt32(0),
        Version = todoReader.GetString(8),
        Type = todoReader.GetString(2),
        Content = todoReader.GetString(3),
        Tip = todoReader.GetString(4)
      });
    }
    await connection.CloseAsync();
  }
  async void LoadProjectList()
  {
    var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
    await connection.OpenAsync();
    var selectProjectCmd = new SqliteCommand("SELECT name FROM project", connection);
    var projectReader = await selectProjectCmd.ExecuteReaderAsync();
    while (await projectReader.ReadAsync())
    {
      ProjectNames.Add(projectReader.GetString(0));
    }
    await connection.CloseAsync();
    Project.ItemsSource = ProjectNames;
    Project.SelectedItem = ProjectNames[0];
    LoadList();
  }
  void ChangeProject(object sender, SelectionChangedEventArgs args)
  {
    LoadList();
  }
  async void FinishUpdate(object sender, RoutedEventArgs args)
  {
    if (sender is Button btn)
    {
      var e = (TodoItem)btn.Tag;
      var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
      await connection.OpenAsync();
      var updateCmd = new SqliteCommand("UPDATE 'update' SET finished=1 WHERE id=" + e.Id, connection);
      await updateCmd.ExecuteNonQueryAsync();
      await connection.CloseAsync();
      LoadList();
    }
  }
}